package ss.pku.meeting.service;

import ss.pku.meeting.entities.Msg;
import ss.pku.meeting.mapper.RepairMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class RepairService {
    @Autowired
    RepairMapper repairMapper;

    public Msg handleRepair(MultipartFile file, int equip, String msg, int id) throws IOException {
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀名。也可以在这里添加判断语句，规定特定格式的图片才能上传，否则拒绝保存。
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //为了避免发生图片替换，这里使用了文件名重新生成
        fileName = UUID.randomUUID().toString().replaceAll("-","")+suffixName;

        String path = ResourceUtils.getURL("classpath:").getPath() + "img";
        File destFile = new File(path);
        if(!destFile.exists()){
            //不存在,则新建一个目录
            destFile.mkdirs();
        }
        try {
            file.transferTo(new File(path + File.separator + fileName));
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败,服务器发生异常！", e);
        }
        repairMapper.insertRepair(id, equip, msg, fileName);
        return Msg.success();
    }
}
